package com.yycx.common.utils;

import com.yycx.common.base.utils.FlymeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtils {

    /**
     * get
     * 发送get请求
     *
     * @param requestUrl  请求路径
     * @param headers     请求头数据,使用map封装
     * @param queryParams 请求参数,使用map封装
     * @return
     * @throws Exception
     */
    public static HttpResponse doGet(String requestUrl, Map<String, String> headers, Map<String, Object> queryParams) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(buildUrl(requestUrl, queryParams));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        System.out.println("requestAllHeaders:" + request.getAllHeaders());
        return httpClient.execute(request);
    }

    /**
     * post form
     *
     * @param requestUrl
     * @param headers
     * @param queryParams
     * @param bodys       请求体,使用map封装
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String requestUrl, Map<String, String> headers, Map<String, Object> queryParams, Map<String, String> bodys) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost request = new HttpPost(buildUrl(requestUrl, queryParams));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<>();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }
        
        System.out.println("requestEntity:" + JsonUtils.beanToJson(request.getEntity()));
        System.out.println("requestAllHeaders:" + request.getAllHeaders());
        return httpClient.execute(request);
    }

    /**
     * Post String
     *
     * @param requestUrl
     * @param headers
     * @param params
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String requestUrl, Map<String, String> headers, Map<String, Object> params, String body)
            throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost request = new HttpPost(buildUrl(requestUrl, params));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }
        System.out.println("requestEntity:" + JsonUtils.beanToJson(request.getEntity()));
        System.out.println("requestAllHeaders:" + request.getAllHeaders());
        return httpClient.execute(request);
    }

    /**
     * Post stream
     *
     * @param requestUrl
     * @param headers
     * @param queryParams
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String requestUrl, Map<String, Object> headers, Map<String, Object> queryParams, byte[] body) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();

        HttpPost request = new HttpPost(buildUrl(requestUrl, queryParams));
        for (Map.Entry<String, Object> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue().toString());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }
        System.out.println("requestEntity:" + JsonUtils.beanToJson(request.getEntity()));
        System.out.println("requestAllHeaders:" + request.getAllHeaders());
        return httpClient.execute(request);
    }

    /**
     * Put String
     *
     * @param requestUrl
     * @param headers
     * @param queryParams
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String requestUrl, Map<String, String> headers, Map<String, Object> queryParams, String body) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();

        HttpPut request = new HttpPut(buildUrl(requestUrl, queryParams));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }
        System.out.println("requestEntity:" + JsonUtils.beanToJson(request.getEntity()));
        System.out.println("requestAllHeaders:" + request.getAllHeaders());
        return httpClient.execute(request);
    }

    /**
     * Put stream
     *
     * @param requestUrl
     * @param headers
     * @param queryParams
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String requestUrl, Map<String, String> headers, Map<String, Object> queryParams, byte[] body) throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPut request = new HttpPut(buildUrl(requestUrl, queryParams));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }
        System.out.println("requestEntity:" + JsonUtils.beanToJson(request.getEntity()));
        System.out.println("requestAllHeaders:" + request.getAllHeaders());
        return httpClient.execute(request);
    }

    /**
     * Delete
     *
     * @param requestUrl
     * @param headers
     * @param queryParams
     * @return
     * @throws Exception
     */
    public static HttpResponse doDelete(String requestUrl, Map<String, String> headers, Map<String, Object> queryParams)
            throws Exception {
        HttpClient httpClient = HttpClientBuilder.create().build();

        HttpDelete request = new HttpDelete(buildUrl(requestUrl, queryParams));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        System.out.println("requestAllHeaders:" + request.getAllHeaders());
        return httpClient.execute(request);
    }

    private static String buildUrl(String requestUrl, Map<String, Object> params) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(requestUrl);
        if (FlymeUtils.isNotEmpty(params)) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, Object> query : params.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && FlymeUtils.isNotEmpty(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (FlymeUtils.isNotEmpty(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue().toString(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }
        return sbUrl.toString();
    }

}
